const { Transform } = require("readable-stream");
const nodePath = require("path");
const minify = require("html-minifier").minify;
/**
 * wxml 处理
 * @description  压缩wxml
 */
exports.uglifyWxmlPlugin = isUglify => {
  return new Transform({
    objectMode: true,
    transform(chunk, enc, cb) {
      if (chunk.isNull() || !chunk.isBuffer() || !isUglify) return cb(null, chunk);
      if (nodePath.extname(chunk.path) != ".wxml") return cb(null, chunk);
      try {
        let minified = minify(String(chunk.contents), {
          collapseWhitespace: true,
          minifyCSS: false,
          minifyJs: true,
          includeAutoGeneratedTags: false,
          keepClosingSlash: true,
          removeComments: true
        });
        chunk.contents = Buffer.from(minified);
      } catch (e) {
        console.error(chunk.path, String(chunk.contents));
        throw e;
      }
      cb(null, chunk);
    }
  });
};
